package com.nf.health.app.homepage.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.customview.DragListView;
import com.nf.health.app.customview.DragListView.onRefreshAndLoadMoreListener;
import com.nf.health.app.customview.HeadListView.HeaderAdapter;
import com.nf.health.app.customview.SwipeView;
import com.nf.health.app.customview.SwipeView.OnSwipeStatusChangeListener;
import com.nf.health.app.models.DetectionHistory;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 中医在线——检测记录
 */
public class DetectionHistoryListActivity extends BaseActivity implements OnMyClickListener{
	private DragListView listview;
	private DetectionHistoryAdapter adapter;
	private List<DetectionHistory> histories = new ArrayList<DetectionHistory>();
	private int pageNo = 1;
	private int pageSize   = 20;
	private int curPos;
	private TextView emptyView;
	private String type;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		type = getIntent().getStringExtra("type");
		setTitleBar(R.layout.titlebar_base);
		ViewUtil.setText(this, R.id.titlebar_title_tv, "检测记录");
		setContent(R.layout.activity_detection_history);

		initView();

	}
	@Override
	protected void onResume() {
		super.onResume();
		pageNo = 1;
		initData("refresh");
	}

	private void initData(String flag) {
		provider.requestDetectionHistory(String.valueOf(pageNo), String.valueOf(pageSize), type, flag);
	}

	private void initView() {
		listview = ViewUtil.getView(this, R.id.listview);
		emptyView = ViewUtil.getView(this, R.id.empty);
		listview.setRefreshableAndLoadMoreable(true, true);
		listview.setOnRefreshAndLoadMoreListener(new onRefreshAndLoadMoreListener() {

			@Override
			public void onRefresh() {
				pageNo = 1;
				initData("refresh");
			}

			@Override
			public void onLoadMore() {
				pageNo++;
				initData("more");
			}
		});
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				onMyItemClick(arg2-1);
			}
		});
	}

	protected LayoutAnimationController getAnimationController() {  
		int duration=500;  
		AnimationSet set = new AnimationSet(true);  

		Animation animation = new AlphaAnimation(0.0f, 1.0f);  
		animation.setDuration(duration);  
		set.addAnimation(animation);  

		animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.5f,  
				Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,  
				0.0f, Animation.RELATIVE_TO_SELF, 0.0f);  
		animation.setDuration(duration);  
		set.addAnimation(animation);  

		LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);  
		controller.setOrder(LayoutAnimationController.ORDER_NORMAL);  
		return controller;  
	}  
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(requestCode==100 && resultCode == RESULT_OK){
			initData("refresh");
		}
	}


	@Override
	public void handleActionSuccess(String actionName, Object object) {
		if("refresh".equals(actionName)){
			listview.completeRefresh();
			//			histories = (List<DetectionHistory>)object;
			histories.clear();
			histories.addAll((List<DetectionHistory>)object);
			if(histories.size()<=0){
				if(adapter!= null){
					adapter.notifyDataSetChanged();
				}
				listview.setRefreshableAndLoadMoreable(false,false);
				listview.setEmptyView(emptyView);
				return;
			}
			if(adapter==null){
				adapter = new DetectionHistoryAdapter();
				listview.setAdapter(adapter);

				adapter.setOnMyClickListener(this);
			}else{
				adapter.notifyDataSetChanged();
			}
		}else if("more".equals(actionName)){
			listview.completeLoadMore();
			List<DetectionHistory> history = (List<DetectionHistory>)object;
			if(history!=null && history.size()>0){
				histories.addAll(history);
				if(adapter==null){
					adapter = new DetectionHistoryAdapter();
					listview.setAdapter(adapter);
				}else{
					adapter.notifyDataSetChanged();
				}
			}else{
				showToast("没有更多数据了");
				pageNo--;
			}
		}else if("del".equals(actionName)){

			showToast("删除成功");

			histories.remove(curPos);
			adapter.notifyDataSetChanged();
			if(histories.size()<=0){
				initData("refresh");
			}
		}
	}

	private void onMyItemClick(int position) {
		if(DetectionHistory.STATUS_NO_DOCTOR.equals(histories.get(position).getIs_accept())){
			Bundle bundle = new Bundle();
			bundle.putString("majorid", histories.get(position).getMajor_id());
			bundle.putString("hospitalid", histories.get(position).getHospitalid());
			//					bundle.putString("hospitalid", "1");//测试
			
			
			ActivityUtils.showActivityForResult(DetectionHistoryListActivity.this, DoctorSelectedActivity.class, bundle,100);
		
		
		
		
		}else if(DetectionHistory.STATUS_NO_PAYMENT.equals(histories.get(position).getIs_accept())){
			Bundle bundle = new Bundle();
			bundle.putString("majorid", histories.get(position).getMajor_id());
			ActivityUtils.showActivityForResult(DetectionHistoryListActivity.this, DoctorSelectedActivity.class, bundle,100);
		}else{
			if("medic".equals(histories.get(position).getType())){
				//中医体检
				Bundle bundle = new Bundle();
				bundle.putInt("type", DetectionResultActivity.TYPE_DETECTION);
				bundle.putString("majorid",histories.get(position).getMajor_id());
				ActivityUtils.showActivity(DetectionHistoryListActivity.this, DetectionResultActivity.class, bundle);
			}else{
				//风险评估
				Bundle bundle = new Bundle();
				bundle.putInt("type", DetectionResultActivity.TYPE_PING_GU);
				bundle.putString("majorid",histories.get(position).getMajor_id());
				ActivityUtils.showActivity(DetectionHistoryListActivity.this, DetectionResultActivity.class, bundle);
			}
		}
	}

	class DetectionHistoryAdapter extends BaseAdapter implements SectionIndexer, HeaderAdapter, OnScrollListener{

		private ArrayList<SwipeView> unClosedSwipeView = new ArrayList<SwipeView>();

		private static final int DELETABLE = 0;
		private static final int UnDELETABLE = 1;
		@Override
		public int getCount() {
			return histories==null?0:histories.size();
		}

		@Override
		public Object getItem(int position) {
			return histories.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getItemViewType(int position) {
			DetectionHistory item = histories.get(position);
			if (DetectionHistory.STATUS_FINISH.equals(item.getIs_accept())
					|| DetectionHistory.STATUS_DISABLE.equals(item.getIs_accept())
					|| DetectionHistory.STATUS_NO_PAYMENT.equals(item.getIs_accept())
					|| DetectionHistory.STATUS_REFUND.equals(item.getIs_accept())) {
				return DELETABLE;
			} else {
				return UnDELETABLE;
			}
		}
		@Override
		public int getViewTypeCount() {
			return 2;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			DetectionHistory item = histories.get(position);
			ViewHolder holder;
			TextView tv_status;
			if(DELETABLE == getItemViewType(position)){
				holder = ViewHolder.get(parent, convertView, R.layout.item_detection_history_deletable, position);
				holder.setText(R.id.tv_content, item.getRisk_evaluation());
				holder.setText(R.id.tv_time, item.getUpdate_time());
				tv_status = holder.getView(R.id.tv_status);
				tv_status.setText(item.getAccept_desc());


				SwipeView swipeView  = holder.getView(R.id.swipeView);
				View delete  = holder.getView(R.id.delete);
				View ll_content  = holder.getView(R.id.ll_content);

				delete.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if(listener != null)
							listener.onClick(position, "");			
						
						unClosedSwipeView.clear();
					}
				});


				ll_content.setTag(position);
				ll_content.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (unClosedSwipeView.size() > 0) {
							closeAllOpenedSwipeView();
						} else {
							int tag = (Integer) v.getTag();
							onMyItemClick(tag);
						}
					}
				});

				swipeView.setOnSwipeStatusChangeListener(new OnSwipeStatusChangeListener() {

					@Override
					public void onOpen(SwipeView openedSwipeView) {
						// TODO Auto-generated method stub
						for (int i = 0; i < unClosedSwipeView.size(); i++) {
							if (unClosedSwipeView.get(i) != openedSwipeView) {
								unClosedSwipeView.get(i).close();
							}
						}
						if (!unClosedSwipeView.contains(openedSwipeView)) {
							unClosedSwipeView.add(openedSwipeView);
						}
					}

					@Override
					public void onClose(SwipeView closedSwipeView) {
						// TODO Auto-generated method stub
						unClosedSwipeView.remove(closedSwipeView);
					}

					@Override
					public void onSwiping(SwipeView swipingSwipeView) {
						// TODO Auto-generated method stub
						if (!unClosedSwipeView.contains(swipingSwipeView)) {
							closeAllOpenedSwipeView();
						}
						if (!unClosedSwipeView.contains(swipingSwipeView)) {
							unClosedSwipeView.add(swipingSwipeView);
						}
					}

				});
			}else{
				holder = ViewHolder.get(parent, convertView, R.layout.item_detection_history, position);
				holder.setText(R.id.tv_content, item.getRisk_evaluation());
				holder.setText(R.id.tv_time, item.getUpdate_time());
				tv_status = holder.getView(R.id.tv_status);
				tv_status.setText(item.getAccept_desc());

			}
			if(DetectionHistory.STATUS_FINISH.equals(item.getIs_accept())
					|| DetectionHistory.STATUS_DISABLE.equals(item.getIs_accept())
					|| DetectionHistory.STATUS_NO_PAYMENT.equals(item.getIs_accept())
					|| DetectionHistory.STATUS_REFUND.equals(item.getIs_accept())){
				tv_status.setTextColor(getResources().getColor(R.color.black8));
			}else{
				tv_status.setTextColor(Color.RED);
			}


			return holder.getConvertView();
		}
		private OnMyClickListener listener;
		public void setOnMyClickListener(OnMyClickListener listener){
			this.listener = listener;
		}

		private void closeAllOpenedSwipeView() {

			for (int i = 0; i < unClosedSwipeView.size(); i++) {
				if (unClosedSwipeView.get(i).getSwipeStatus() != SwipeView.SwipeStatus.Close) {
					unClosedSwipeView.get(i).close();
				}
			}
		}

		@Override
		public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onScrollStateChanged(AbsListView arg0, int arg1) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public int getHeaderState(int position) {
			// TODO Auto-generated method stub
			int realPosition = position;
			if (realPosition < 0 || position >= getCount()) {
				return HEADER_GONE;
			}
			int section = getSectionForPosition(realPosition);
			int nextSectionPosition = getPositionForSection(section + 1);
			if (nextSectionPosition != -1
					&& realPosition == nextSectionPosition - 1) {
				return HEADER_PUSHED_UP;
			}
			return HEADER_VISIBLE;
		}

		@Override
		public void configureHeader(View header, int position, int alpha) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public int getPositionForSection(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public int getSectionForPosition(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public Object[] getSections() {
			// TODO Auto-generated method stub
			return null;
		}

	}

	@Override
	public void onClick(int position, String flag) {
		String is_accept = histories.get(position).getIs_accept();
		if (DetectionHistory.STATUS_FINISH.equals(is_accept)
				|| DetectionHistory.STATUS_DISABLE.equals(is_accept)
				|| DetectionHistory.STATUS_NO_PAYMENT.equals(is_accept)
				|| DetectionHistory.STATUS_REFUND.equals(is_accept)) {
			curPos = position;
			provider.requestDelDetectionHistory(histories.get(position).getMajor_id(), "del");
		}else{
			showToast("这条记录不可删除");
		}
	}
}
